<template>
  <div class="cart-container">
    <div class="header-nav">
      <el-button
        type="primary"
        icon="el-icon-back"
        @click="goBack"
        class="back-btn"
      >
        返回首页
      </el-button>
    </div>
    <el-card class="cart-card">
      <el-table
        :data="cartItems"
        stripe
        style="width: 100%;"
      >
        <!-- 修改 prop 为 title -->
        <!-- 在表格中添加库存列 -->
        <el-table-column prop="stock" label="库存" width="100"></el-table-column>
        <el-table-column prop="title" label="商品名称" width="200"></el-table-column>
        <el-table-column prop="price" label="单价" width="100">
          <template slot-scope="scope">
            ¥ {{ scope.row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="数量" width="180">
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.quantity"
              :min="1"
              :max="scope.row.stock"
              size="small"
              controls-position="right"
              @change="(value) => updateQuantity(value, scope)"
              class="quantity-input"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="总价" width="100">
          <template slot-scope="scope">
            ¥ {{ (scope.row.price * scope.row.quantity).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-button
              type="danger"
              size="small"
              @click="deleteItem(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <div class="checkout-bar">
      <div class="total-price">
        总计：<span class="price">¥ {{ totalPrice.toFixed(2) }}</span>
      </div>
      <div class="actions">
        <el-button
          type="primary"
          @click="clearCart"
        >
          清空购物车
        </el-button>
        <el-button
          type="primary"
          @click="checkout"
        >
          去结算
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'CartView',
  data() {
    return {
      selectedItem: null,
      deleteVisible: false
    };
  },
  computed: {
    cartItems() {
      return this.$store.state.cartItems;
    },
    totalPrice() {
      return this.$store.getters.cartTotal;
    }
  },
  methods: {
    goBack() {
      this.$router.go(-1);
    },
    async updateQuantity(value, scope) {
      const item = scope.row;
      const book = this.$store.state.books.find(b => b.id === item.id);
      
      if (book && value > book.stock) {
        this.$message.warning(`库存不足，当前库存为${book.stock}`);
        this.$store.commit('updateCartItemQuantity', { bookId: item.id, quantity: book.stock });
        return;
      }
      
      this.$store.commit('updateCartItemQuantity', { bookId: item.id, quantity: value });
    },
    deleteItem(item) {
      this.$confirm('确定要删除这个商品吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.commit('removeFromCart', item.id);
        this.$message.success('商品已移除');
      }).catch(() => {});
    },
    clearCart() {
      this.$confirm('确定要清空购物车吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.commit('clearCart');
        this.$message.success('购物车已清空');
      }).catch(() => {});
    },
    checkout() {
      if (!this.$store.state.user) {
        this.$message.warning('请先登录');
        this.$router.push({
          path: '/login',
          query: { redirect: '/checkout' }
        });
        return;
      }

      if (this.cartItems.length === 0) {
        this.$message.warning('购物车为空');
        return;
      }

      // 确保在跳转前更新购物车数据
      this.$store.commit('updateCartItems', this.cartItems);
      this.$router.push('/checkout');
    }
  },
  created() {
    if (!this.$store.state.user) {
      this.$message.warning('请先登录');
      this.$router.push({
        path: '/login',
        query: { redirect: '/cart' }
      });
      return;
    }
  },
  watch: {
    cartItems: {
      handler() {
        // 当购物车数据变化时，确保页面数据更新
        this.$forceUpdate();
      },
      deep: true
    }
  }
};
</script>

<style scoped>
.cart-container {
  padding: 30px;
  background: #f5f7fa;
  min-height: 100vh;
}

.cart-card {
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

.header-nav {
  margin-bottom: 20px;
}

.back-btn {
  padding: 12px 25px;
  border-radius: 8px;
  transition: all 0.3s;
}

.back-btn:hover {
  transform: translateX(-5px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.checkout-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  margin-top: 20px;
}

.total-price {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.price {
  color: #f56c6c;
  font-size: 24px;
  margin-left: 10px;
}

.actions {
  display: flex;
  gap: 10px;
}

.quantity-input {
  width: 120px;
}

.quantity-input .el-input-number__decrease,
.quantity-input .el-input-number__increase {
  background-color: #f5f7fa;
  border: 1px solid #dcdfe6;
  color: #606266;
  width: 32px;
  height: 32px;
  line-height: 32px;
  text-align: center;
  position: absolute;
  z-index: 1;
  top: 1px;
  border-radius: 4px;
  transition: all 0.3s;
}

.quantity-input .el-input-number__decrease {
  left: 1px;
  border-right: 0;
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}

.quantity-input .el-input-number__increase {
  right: 1px;
  border-left: 0;
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}

.quantity-input .el-input-number__decrease:hover,
.quantity-input .el-input-number__increase:hover {
  color: #409EFF;
  background-color: #ecf5ff;
}

.quantity-input .el-input-number__decrease:active,
.quantity-input .el-input-number__increase:active {
  color: #fff;
  background-color: #409EFF;
}

.quantity-input .el-input__inner {
  text-align: center;
  padding-left: 32px;
  padding-right: 32px;
}
</style>